//
//  HomeController.swift
//  SCA
//
//  Created by tjun on 2025/9/1.
//

import UIKit
import FSPagerView



class HomeController: BaseController {
    
    private var bannerUrls: [String] = []
    private var pagerView: FSPagerView!
    private var pageControl: FSPageControl!
    private let headerView = UIView(frame: CGRectMake(0, 0, screenWidth, 764))
    
    private let SCATotalCirculationView = TextSubTextView()
    private let SCA24HOutputView = TextSubTextView()
    
    private let AIATotalCirculationView = TextSubTextView()
    private let AIA24HOutputView = TextSubTextView()
    
    private let AIDTotalCirculationView = TextSubTextView()
    private let AID24HOutputView = TextSubTextView()
    
    private var newsDatas: [NewsListModel] = []
    
    private var lastView: UIView?
    private let coinView = SCACoinView()
    
    private let tipSet2FAView = GradientTipView(text: "请尽快设置双重验证（2FA），以保障您的资产安全。".localizedString)
    private let tipSetPinView = GradientTipView(text: "请尽快设置二级安全密码，以保障您的资产安全。".localizedString)
    private let powerCircleView = PowerCircleView()
    private let powerValueView = PowerValueView()

    private lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = AppStyle.color.background
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 100
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(NewsListCell.self, forCellReuseIdentifier: NewsListCell.identifier)
        return tableView
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBarUI()
        addHeaderView()
        
        tableView.tableHeaderView = headerView
        tableView.addTo(view)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(navBarHeight)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadHeaderData), name: NotificationName.pin2faStateChange, object: nil)
        
        reloadHeaderData()
        loadData()
    }
    
    private func addHeaderView() {
        
        pagerView = FSPagerView()
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        pagerView.dataSource = self
        pagerView.delegate = self
        pagerView.isInfinite = true
        pagerView.transformer = nil
        pagerView.interitemSpacing = 0
        
        pagerView.layer.cornerRadius = 10
        pagerView.layer.masksToBounds = true
        pagerView.automaticSlidingInterval = 3.0
        pagerView.itemSize = FSPagerView.automaticSize
        
        let bannerLeftRightMargin = 20
        let bannerH = (Int(view.width) - bannerLeftRightMargin * 2) * 607 / 1080
        headerView.addSubview(pagerView)
        pagerView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(bannerLeftRightMargin)
            make.top.equalTo(5)
            make.height.equalTo(bannerH)
        }
        
        pageControl = FSPageControl()
        pageControl.contentHorizontalAlignment = .center
        pagerView.addSubview(pageControl)
        pageControl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(20)
            make.width.equalTo(200)
        }
        
        coinView.addTo(headerView)
        coinView.addTapGesturesWithTarget(target: self, action: #selector(coinViewTapped))
        coinView.snp.makeConstraints { make in
            make.top.equalTo(pagerView.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(75)
        }
        
        let computingPowerLineView = TitleLineView().addTo(headerView)
        computingPowerLineView.titleLabel.text = "全网总算力".localizedString
        computingPowerLineView.snp.makeConstraints { make in
            make.left.right.equalTo(pagerView)
            make.top.equalTo(coinView.snp.bottom)
        }
        
        powerCircleView.addTo(headerView)
        powerCircleView.setCenterText(top: "算力".localizedString, value: "0.00", unit: "G")
        powerCircleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(50)
            make.width.equalTo(146.scaled)
            make.top.equalTo(computingPowerLineView.snp.bottom).offset(10)
            make.height.equalTo(200)
        }
        
        powerValueView.addTo(headerView)
        powerValueView.onPowerCircleInfoTapped = {[weak self] model in
            guard let weakSelf = self else { return }
            
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 3
            paragraphStyle.paragraphSpacing = 5
            paragraphStyle.alignment = .center

            let attributedText = NSAttributedString(
                string: model.totalDisp,
                attributes: [
                    .font: UIFont.systemFont(ofSize: 20, weight: .bold),
                    .foregroundColor: UIColor.white,
                    .paragraphStyle: paragraphStyle
                ]
            )
            
            PowerValueAlertController(title: model.title, attributedText: attributedText).showIn(weakSelf)
        }
        powerValueView.snp.makeConstraints { make in
            make.left.equalTo(powerCircleView.snp.right).offset(50)
            make.right.equalTo(-AppStyle.margin.left)
            make.top.equalTo(powerCircleView)
            make.height.equalTo(powerCircleView)
        }
        
        let powerInfoView = UIView().addTo(headerView)
        powerInfoView.addSubview(SCATotalCirculationView)
        powerInfoView.addSubview(SCA24HOutputView)
        powerInfoView.addSubview(AIATotalCirculationView)
        powerInfoView.addSubview(AIA24HOutputView)
        powerInfoView.addSubview(AIDTotalCirculationView)
        powerInfoView.addSubview(AID24HOutputView)
        

        SCATotalCirculationView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        SCA24HOutputView.snp.makeConstraints { make in
            make.centerY.equalTo(SCA24HOutputView)
            make.right.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        AIATotalCirculationView.snp.makeConstraints { make in
            make.top.equalTo(SCATotalCirculationView.snp.bottom).offset(16)
            make.left.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        AIA24HOutputView.snp.makeConstraints { make in
            make.centerY.equalTo(AIATotalCirculationView)
            make.right.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        AIDTotalCirculationView.snp.makeConstraints { make in
            make.top.equalTo(AIATotalCirculationView.snp.bottom).offset(16)
            make.left.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        AID24HOutputView.snp.makeConstraints { make in
            make.centerY.equalTo(AIDTotalCirculationView)
            make.right.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        //不能删除
        SCATotalCirculationView.textLabel.text = "当前流通总量 （SCA)".localizedString
        SCATotalCirculationView.subTextLabel.text = "0.0000"
        
        SCA24HOutputView.textLabel.text = "24小时产出 (SCA)".localizedString
        SCA24HOutputView.subTextLabel.text = "0.0000"
        
        AIATotalCirculationView.textLabel.text = "当前流通总量 （AIA)".localizedString
        AIATotalCirculationView.subTextLabel.text = "0.0000"
        
        AIA24HOutputView.textLabel.text = "24小时产出 (AIA)".localizedString
        AIA24HOutputView.subTextLabel.text = "0.0000"
        
        AIDTotalCirculationView.textLabel.text = "当前流通总量 （AID)".localizedString
        AIDTotalCirculationView.subTextLabel.text = "0.0000"
        
        AID24HOutputView.textLabel.text = "24小时产出 (AID)".localizedString
        AID24HOutputView.subTextLabel.text = "0.0000"
        
        powerInfoView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.top.equalTo(powerCircleView.snp.bottom)
            make.bottom.equalTo(AID24HOutputView)
        }
        
        let newsLineView = TitleLineView().addTo(headerView)
        newsLineView.titleLabel.text = "资讯".localizedString
        newsLineView.snp.makeConstraints { make in
            make.top.equalTo(powerInfoView.snp.bottom).offset(10)
            make.left.right.equalTo(pagerView)
        }
        lastView = newsLineView
    }
    
    @objc private func coinViewTapped() {
        let tokenPriceController = TokenPriceController()
        tokenPriceController.model = self.coinView.model
        navigationController?.pushViewController(tokenPriceController, animated: true)
    }
    
    private func setNavigationBarUI() {
        
        navigationBar.title = nil
        
        let infoButton = UIButton(image: UIImage(named: "nav_mine_info"), target: self, action: #selector(infoButtonTapped))
        navigationBar.contentView.addSubview(infoButton)
        infoButton.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        let logoImageView = UIImageView(image: UIImage(named: "nav_logo"))
        navigationBar.contentView.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let logoutButton = UIButton(image: UIImage(named: "nav_logout"), target: self, action: #selector(logoutButtonTapped))
        navigationBar.contentView.addSubview(logoutButton)
        logoutButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        tipSet2FAView.addTapGesturesWithTarget(target: self, action: #selector(tipSet2FAViewTapped))
        tipSetPinView.addTapGesturesWithTarget(target: self, action: #selector(tipSetPinViewTapped))
    }
    
    @objc func tipSet2FAViewTapped() {
        let validatorBindingController = ValidatorBindingController()
        navigationController?.pushViewController(validatorBindingController, animated: true)
    }
    
    @objc func tipSetPinViewTapped() {
        let validatorBindingController = ModifySecondaryPasswordController()
        navigationController?.pushViewController(validatorBindingController, animated: true)
    }
    
    @objc func reloadHeaderData() {
        
        tipSet2FAView.removeFromSuperview()
        tipSetPinView.removeFromSuperview()
        
        let userInfoModel = UserInfoModel.current
        if !userInfoModel.isSet2fa, !userInfoModel.isSetPin {
            
            tipSet2FAView.addTo(headerView)
            tipSet2FAView.snp.remakeConstraints { make in
                make.top.equalTo(pagerView.snp.bottom).offset(14)
                make.left.right.equalTo(pagerView)
                make.height.equalTo(36)
            }
            
            tipSetPinView.addTo(headerView)
            tipSetPinView.snp.remakeConstraints { make in
                make.top.equalTo(tipSet2FAView.snp.bottom).offset(10)
                make.left.right.height.equalTo(tipSet2FAView)
            }
            
            coinView.snp.remakeConstraints { make in
                make.top.equalTo(tipSetPinView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.height.equalTo(75)
            }
            
        } else if !userInfoModel.isSet2fa {
            
            tipSet2FAView.addTo(headerView)
            tipSet2FAView.snp.remakeConstraints { make in
                make.top.equalTo(pagerView.snp.bottom).offset(14)
                make.left.right.equalTo(pagerView)
                make.height.equalTo(36)
            }
            
            coinView.snp.remakeConstraints { make in
                make.top.equalTo(tipSet2FAView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.height.equalTo(75)
            }
            
        } else if !userInfoModel.isSetPin {
            
            tipSetPinView.addTo(headerView)
            tipSetPinView.snp.remakeConstraints { make in
                make.top.equalTo(pagerView.snp.bottom).offset(14)
                make.left.right.equalTo(pagerView)
                make.height.equalTo(36)
            }
            
            coinView.snp.remakeConstraints { make in
                make.top.equalTo(tipSetPinView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.height.equalTo(75)
            }
        } else {
            coinView.snp.remakeConstraints { make in
                make.top.equalTo(pagerView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.height.equalTo(75)
            }
        }
                
        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()
    
        headerView.frame = CGRectMake(0, 0, screenWidth, lastView!.maxY + 10)
        tableView.tableHeaderView = headerView
        tableView.reloadData()
    }
    
    private func loadData() {
        HomeService.loadBannersData { urls in
            self.bannerUrls.removeAll()
            self.bannerUrls.append(contentsOf:urls)
            self.pageControl.numberOfPages = urls.count
            self.pagerView.reloadData()
        }
        
        NewsService.loadNewsListData(limit: 5, type: .news) { models in
            self.newsDatas.append(contentsOf: models)
            self.tableView.reloadData()
        }
        
        HomeService.loadTokensPriceData { model in
            self.coinView.model = model
        }
        
        HomeService.loadWorldPowerOverviewData { powerOverviewModel in
            
            let powerInfo = powerOverviewModel.power
            self.powerCircleView.powerInfo = powerInfo
            self.powerValueView.powerInfo = powerInfo
            
            guard let scaInfoModel = powerOverviewModel.bonus[.sca],
                  let aiaInfoModel = powerOverviewModel.bonus[.aia],
                  let aidInfoModel = powerOverviewModel.bonus[.aid] else {
                return
            }
            
            self.SCATotalCirculationView.textLabel.text = scaInfoModel.totalTitle
            self.SCATotalCirculationView.subTextLabel.text = scaInfoModel.totalDisp
            self.SCA24HOutputView.textLabel.text = scaInfoModel.dailyTitle
            self.SCA24HOutputView.subTextLabel.text = scaInfoModel.dailyDisp
            
            self.AIATotalCirculationView.textLabel.text = aiaInfoModel.totalTitle
            self.AIATotalCirculationView.subTextLabel.text = aiaInfoModel.totalDisp
            self.AIA24HOutputView.textLabel.text = aiaInfoModel.dailyTitle
            self.AIA24HOutputView.subTextLabel.text = aiaInfoModel.dailyDisp
            
            self.AIDTotalCirculationView.textLabel.text = aidInfoModel.totalTitle
            self.AIDTotalCirculationView.subTextLabel.text = aidInfoModel.totalDisp
            self.AID24HOutputView.textLabel.text = aidInfoModel.dailyTitle
            self.AID24HOutputView.subTextLabel.text = aidInfoModel.dailyDisp
        }
    }
    
    @objc func infoButtonTapped() {
        let mineController = MineController()
        mineController.showInController(self)
    }
    
    @objc func logoutButtonTapped() {
        NotificationCenter.default.post(name: NotificationName.userLogout, object: nil)
    }
    
}


extension HomeController: FSPagerViewDataSource, FSPagerViewDelegate {
    
    // MARK: - FSPagerViewDataSource
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannerUrls.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.imageView?.setImage(url: bannerUrls[index])
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        return cell
    }
    
    // MARK: - FSPagerViewDelegate
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        print("点击了第\(index)张图")
        let models: [PhotoModel] = bannerUrls.map { url in
            let model = PhotoModel()
            model.type = .image
            model.url = url
            return model
        }
        PhotoPreviewController.showIn(self, photos: models, index: index)
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        pageControl.currentPage = pagerView.currentIndex
    }
}


extension HomeController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsDatas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NewsListCell.identifier, for: indexPath) as! NewsListCell
        let model = newsDatas[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = newsDatas[indexPath.row]
        let detailController = NewsDetailController(model: model)
        present(detailController, animated: true)
    }
    
}


